package me.hetong.wechat;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import me.hetong.tool.TtBase62Tool;

import java.util.HashMap;
import java.util.Map;

@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class TtWechat {

    private String appId;
    private String secret;

    /**
     * 获取accessToken
     *
     * @return
     */
    public AccessToken getAccessToken() {
        try {
            String url = "https://api.weixin.qq.com/cgi-bin/token?appid=" +
                    this.appId +
                    "&secret=" +
                    this.secret +
                    "&js_code=" +
                    "&grant_type=client_credential";
            StaticLog.info("微信小程序-获取accessToken地址:{}", url);
            final String res = HttpUtil.get(url);
            StaticLog.info("微信小程序-获取accessToken返回:{}", res);
            /**
             * 返回示例：
             * {
             * "access_token": "41_NozGtqlU4ulkUU-8lXo4luRD-m7opuNrjdwwQ3YotQiYS9HTQ8G0iukv_kVvO_KU2yc6QNsBuGxT6YjCK8eYXsn_wYMN8yChb-WVlAI5QKWFIR_XyCPhGGp-wrHbGJ_mPan7nFqSy7B3H4yoJLWbAFAQSD",
             * "expires_in": 7200
             * }
             */
            return JSONUtil.toBean(res, AccessToken.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取小程序二维码
     *
     * @param accessToken
     * @param scene       小程序参数，如：deviceCode=ok
     * @param page        跳转地址，如：pages/water/index
     * @return
     */
    public byte[] getQrCodeByte(String accessToken, String page, String scene) {
        try {
            String url = StrUtil.format("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={}", accessToken);
            HttpRequest post = HttpUtil.createPost(url);

            Map<String, Object> map = new HashMap<>();
            map.put("scene", scene);
            map.put("page", page);
//            map.put("env_version", "release");// 要打开的小程序版本。正式版为 "release"，体验版为 "trial"，开发版为 "develop"。默认是正式版。
            String s = JSONUtil.toJsonStr(map);
            StaticLog.info("小程序码-请求参数:{}", s);
            post.body(s);
            HttpResponse res = post.execute();
            if (res.getStatus() == 200) {
                return res.bodyBytes();
            }
        } catch (Exception e) {
            StaticLog.info("小程序码-调用接口异常:{}", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将跳转页面与参数hash计算编码
     *
     * @param page
     * @param queryParam
     * @return
     */
    public static String getCode(String page, String queryParam) {
        String md5 = SecureUtil.md5(page + queryParam);
        return TtBase62Tool.hexToBase62(md5);
    }

    @Data
    public class AccessToken {
        private String access_token;
        private String expires_in;
    }

    public static void main(String[] args) {
//        MyOssTool.init();
        TtWechat ttWechat = new TtWechat();
        ttWechat.setAppId("wxc89e1439f9987f55");
        ttWechat.setSecret("3353357eaa37a64e49460eeb3eff4e072");
//        AccessToken token = ttWechat.getAccessToken();
//        System.out.println(token.getAccess_token());
//        byte[] qrCodeByte = ttWechat.getQrCodeByte("91_IhKdDm-KIFFJrhbIBYRQxnQ1bTApmPnrIli9gB48PjgDl-TWbZDaCEh5d9pnG4A6Lm43uxSFSgpnt0o-D81PWiO1hEtosYJdPd8OMVUASZz5VMqIfbSAYFcZi-YCMHbAJAMWR", "ourkey=lkadj871298", "pages/idCard");
//        FileUtil.writeBytes(qrCodeByte, "C:\\Users\\BCTC\\Downloads\\2.png");
//        FileUtil
//        String upload = MyOssTool.ttOSS.upload(qrCodeByte, ".png");
//        System.out.println(upload);
//        String code = ttWechat.getCode("pages/idCard", "userId=12423dsfdsfasdf");
//        System.out.println(code);
//        String encode = ;
//        System.out.println("中国虽：" + encode);
    }
}
